package com.study.cloud.gateway.core.netty.process;

import com.study.cloud.gateway.common.enums.ResponseCode;
import com.study.cloud.gateway.common.exception.BaseException;
import com.study.cloud.gateway.common.exception.ConnectException;
import com.study.cloud.gateway.common.exception.ResponseException;
import com.study.cloud.gateway.common.response.GatewayResponse;
import com.study.cloud.gateway.core.config.ConfigLoader;
import com.study.cloud.gateway.core.context.GatewayContext;
import com.study.cloud.gateway.core.context.HttpRequestWrapper;
import com.study.cloud.gateway.core.filter.FilterChainFactory;
import com.study.cloud.gateway.core.filter.GatewayFilterChainFactory;
import com.study.cloud.gateway.core.helper.AsyncHttpHelper;
import com.study.cloud.gateway.core.helper.RequestHelper;
import com.study.cloud.gateway.core.helper.ResponseHelper;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.Request;
import org.asynchttpclient.Response;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;

/**
 * @author wangwancheng
 * @create 2025/7/19 09:50
 */
@Slf4j
public class NettyCoreProcessor implements NettyProcessor{

    private FilterChainFactory filterChainFactory = GatewayFilterChainFactory.getInstance();


    @Override
    public void process(HttpRequestWrapper httpRequestWrapper) {
        FullHttpRequest request = httpRequestWrapper.getFullHttpRequest();
        ChannelHandlerContext ctx = httpRequestWrapper.getChannelHandlerContext();
        try {
            //1.创建 网关的上下文
            GatewayContext gatewayContext = RequestHelper.doContext(request, ctx);
            //2.调用过滤器
            filterChainFactory.build(gatewayContext).doFilter(gatewayContext);
            //3.路由请求获取信息
           // route(gatewayContext);
        }catch (BaseException e){
            log.error("process error {} {}",e.getCode().getCode(),e.getCode().getMessage(),e);
            FullHttpResponse fullHttpResponse = ResponseHelper.getHttpResponse(e.getCode());
            doWriteAndRelease(ctx,request,fullHttpResponse);
        }catch (Exception e){
            log.error("请求处理异常",e);
            log.error("process unknow error  ",e);
            FullHttpResponse fullHttpResponse = ResponseHelper.getHttpResponse(ResponseCode.INTERNAL_ERROR);
            doWriteAndRelease(ctx,request,fullHttpResponse);
        }

    }

    private void doWriteAndRelease(ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse fullHttpResponse) {
        ctx.writeAndFlush(fullHttpResponse)
                .addListener(ChannelFutureListener.CLOSE);
        ReferenceCountUtil.release(request);
    }



}
